﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Vowei.Core.Models;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace Vowei.Data.Models
{
    [Serializable]
    public class DbResourceAssignment : ResourceAssignment
    {
        public DbResourceAssignment()
        {
        }

        protected DbResourceAssignment(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }

        public void InitTypeFromStore()
        {
            var formatter = new BinaryFormatter();
            using (var stream = new MemoryStream(_assignmentSettings, false))
            {
                var obj = (ResourceAssignment)formatter.Deserialize(stream);
                Exceptions = obj.Exceptions;
            }
        }

        private void PersistInstance()
        {
            var formatter = new BinaryFormatter();
            using (var stream = new MemoryStream())
            {
                formatter.Serialize(stream, this);
                _assignmentSettings = stream.ToArray();
            }
        }

        private byte[] _assignmentSettings;

        public byte[] AssignmentSettings
        {
            get
            {
                if (_assignmentSettings == null)
                    PersistInstance();

                return _assignmentSettings;
            }
            set
            {
                if (value != _assignmentSettings)
                {
                    _assignmentSettings = value;
                    InitTypeFromStore();
                }
            }
        }
    }
}
